<template>
  <div class="page-login">
    <a class="logo cursor-pointer"></a>
    <div class="body">
      <div class="form-container">
        <div :class="`bg-${type}`" @click="toggleLoginType" v-if="step === 0"></div>
        <h3 class="login-title">{{ step === 0 ? (type === 'qrcode' ? '微信扫码登录' : '蒲公英运营中心') : (type === 'qrcode' ? '关联已有账号' : '微信授权') }}</h3>
        <div class="qrcode-container" v-if="type==='qrcode' && step === 0 || type === 'password' && step === 1">
          <iframe
            frameborder="0"
            scrolling="no"
            :src="qrconnect_url"
          >
          </iframe>
          <div class="expiration-mask" v-if="isExpiration">
            二维码已过期
          </div>
          <div class="tips mt-30">
            请使用微信扫一扫{{ type==='qrcode' && step === 0 ? '登录' : '授权' }}
            <a class="ml-5" @click="signQrconnectUrl">刷新</a>
            &nbsp;<i :class="`iconfont${refreshing ? ' spinner' : ''}`">&#xe653;</i>
          </div>
        </div>
        <el-form v-if="(type==='password' && step === 0) || (type === 'qrcode' && step === 1)" :model="loginData" :rules="rules" ref="ruleForm">
          <el-form-item class="mt-40 custom-form-item" prop="login_name">
            <el-input
              ref="login-name"
              placeholder="请输入用户名"
              v-model="loginData.login_name"
              class="custom-loign-input"
              @keyup.enter.native="handleLogin"
            >
              <i slot="prefix" class="iconfont" style="font-size: 20px">&#xe656;</i>
            </el-input>
          </el-form-item>
          <el-form-item class="mt-40 custom-form-item" prop="password">
            <el-input
              type="password"
              ref="login-password"
              placeholder="请输入密码"
              v-model="loginData.password"
              class="custom-loign-input"
              @keyup.enter.native="handleLogin"
            >
              <i slot="prefix" class="iconfont" style="font-size: 20px">&#xe655;</i>
            </el-input>
          </el-form-item>
          <el-form-item class="mt-50">
            <el-button type="primary" class="w-100" @click="handleLogin" id="btn-submit" :disabled="loading">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { Form, FormItem, Button, Input, Checkbox, Message } from 'element-ui';
import { Config, Http, Method } from '@/util';
import md5 from 'md5';

export default {
  name: 'login',
  components: {
    'el-form': Form,
    'el-form-item': FormItem,
    'el-button': Button,
    'el-input': Input,
    'el-checkbox': Checkbox
  },
  created() {
    documentTitle('登录');
    this.$data.type === 'qrcode' && this.signQrconnectUrl();
  },
  beforeDestroy() {
    this.interval && clearInterval(this.interval);
  },
  data() {
    return {

      type: 'qrcode', //  qrcode | password
      step: 0,

      isDev: Config.isDev,
      refreshing: false, // 刷新二维码
      loading: false, // 提交loading
      isExpiration: false,

      login_key: '',
      qrconnect_url: '',

      loginData: {
        login_name: '',
        password: '',
      },

      wechatInfo: {
        snsapi_openid: '',
        wechat_unionid: '',
      },
      rules: {
        login_name: [
          { required: true, message: '用户名不能为空', trigger: 'change' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'change' }
        ]
      }
    }
  },

  methods: {

    /**
     * 账号密码 + 扫码:
     *  /m/sign/login 返回的login_key、qrconnect_url
     *  轮询: /sign/login/confirm 参数login_key
     *
     * 直接扫码:
     *  /m/sign/qrconnect/url
     *  轮询: /sign/login/confirm 参数login_key
     *
     * 登陆失败账号绑定:
     *  /sign/wechat/bind  参数: login_name、password、snsapi_openid、wechat_unionid
     */
    intervalConfirm() {
      this.interval = setInterval(() => {
        Http.post(Config.api.signLoginConfirm, { login_key: this.$data.login_key }, { throttle: false })
          .then(res => {

            if (res.code === 0) { // 表示绑定成功 或者 登录成功
              this.interval && clearInterval(this.interval);
              this.$router.replace({ name: "Home" });
              return;
            }

            if (res.code == 2) { // 表示需要绑定账号密码
              this.interval && clearInterval(this.interval);
              this.$data.wechatInfo = res.data;
              this.$data.step = 1;
              return;
            }

            if (res.code === 9) { // 表示二维码已过期
              this.interval && clearInterval(this.interval);
              this.$data.isExpiration = true;
              return;
            }

            if (res.code === 1) { // 登录报错
              this.interval && clearInterval(this.interval);
              Message.error({ message: res.message, offset: 100 });
              return;
            }

          });
      }, 2000);
    },

    toggleLoginType() {
      this.interval && clearInterval(this.interval);
      if (this.$data.type === 'qrcode') {
        this.$data.type = 'password';
      } else if (this.$data.type === 'password') {
        this.$data.type = 'qrcode';
        this.signQrconnectUrl();
      }
      this.$data.step = 0;
    },

    // 如果是切换到了 qrcode 登录，则自动刷新URL
    async signQrconnectUrl() {

      this.$data.login_key = '';
      this.$data.qrconnect_url = '';
      this.interval && clearInterval(this.interval); // 请求二维码时，首先重置url 和 计时器

      if (this.$data.refreshing) return;

      this.$data.refreshing = true;
      let res = await Http.get(Config.api.signQrconnectUrl);
      this.$data.refreshing = false;

      if (res.code !== 0) return;
      this.$data.isExpiration = false; // 二维码请求成功后，设定过期状态为false
      this.intervalConfirm(); // 二维码请求成功后，开始计时器
      this.$data.login_key = res.data.login_key;
      this.$data.qrconnect_url = res.data.qrconnect_url;
    },

    handleLogin() {
      this.$refs['ruleForm'].validate(async (valid, vs) => {

        if (!valid) {
          if (vs.login_name) {
            this.$refs['login-name'] && this.$refs['login-name'].focus();
          } else if(vs.password) {
            this.$refs['login-password'] && this.$refs['login-password'].focus();
          }
          return;
        }

        // 用户输入合法校验通过。
        if (this.$data.type === 'qrcode' && this.$data.step === 1) { // 表示当前是绑定微信操作
          let formData = { ...this.$data.loginData, ...this.$data.wechatInfo };
          formData.password = md5(formData.password);

          this.$data.loading = true;
          let res = await Http.post(Config.api.signWechatBind, formData);
          this.$data.loading = false;

          if (res.code === 0) {
            this.$router.replace({ name: "Home" });
          } else {
            this.$message({message: res.message, type: 'error'});
          }
        }

        if (this.$data.type === 'password' && this.$data.step === 0) { // 表示当前是用户输入用户名和密码登录
          let formData = { ...this.$data.loginData };
          formData.password = md5(formData.password);

          this.$data.loading = true;
          let res = await Http.post(Config.api.signLogin, formData, {throttle: false});
          this.$data.loading = false;

          if (res.code === 0) {
            this.$data.login_key = res.data.login_key;
            this.$data.qrconnect_url = res.data.qrconnect_url;
            this.$data.step = 1;
            this.intervalConfirm();

            // //如果是测试开发环境
            this.$data.isDev && Method.setLocalStorage('loginData', formData);
          }else{
            this.$message({message: res.message, type: 'error'});
          }
        }

      });
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
  .page-login {
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
    overflow: hidden;
  }

  .page-login .logo {
    display: inline-block;
    width: 175px;
    height: 68px;
    background: url("./../assets/img/logo_default.png") no-repeat center center;
    background-size: cover;

    position: absolute;
    top: 40px;
    left: 60px;
  }

  .page-login .body {
    width: 900px;
    height: 400px;
    position: absolute;
    top: 50%;
    margin-top: -200px;
    left: 50%;
    margin-left: -450px;
    border-radius: 12px;

    background: url("") no-repeat 30px center;
    background-size: contain;
    background-color: #FFF;
  }

  .body .form-container {
    display: block;
    margin-left: auto;
    width: 380px;
    height: 100%;
    background: #FFFFFF;
    box-shadow: 0 0 20px 0 rgba(0,0,0,0.08);
    border-radius: 12px;
    border-radius: 12px;
    position: relative;
    padding: 40px;
    box-sizing: border-box;
    overflow: hidden;
  }

  .body .form-container .login-title {
    font-weight: 600;
    font-size: 30px;
    line-height: 42px;
    color: #242424;
    user-select: none;
  }

  .body .form-container .bg-password,
  .body .form-container .bg-qrcode {
    position: absolute;
    right: 0;
    top: 0;
    width: 80px;
    height: 80px;
    background-size: cover;
    cursor: pointer;
  }

  .body .form-container .bg-password {
    background: url("") no-repeat center center;
    transition: all .3s ease-in-out;

    &:hover {
      background-image: url("");
    }

    &::after {
      display: inline-block;
      content: '账号登录';
      text-align: center;
      font-size: 12px;
      color: #BBBBBB;
      width: 68px;
      height: 20px;
      line-height: 20px;
      background: url("") no-repeat center center;
      background-size: cover;

      position: absolute;
      top: 13px;
      right: 80px;
    }
  }

  .body .form-container .bg-qrcode {
    background: url("") no-repeat center center;
    transition: all .3s ease-in-out;

    &:hover {
      background-image: url("");
    }

    &::after {
      display: inline-block;
      content: '扫码登录';
      text-align: center;
      font-size: 12px;
      color: #BBBBBB;
      width: 68px;
      height: 20px;
      line-height: 20px;
      background: url("") no-repeat center center;
      background-size: cover;

      position: absolute;
      top: 13px;
      right: 80px;
    }
  }

  .body .qrcode-container {
    margin-top: 28px;
    width: 300px;
    height: 330px;
    overflow: hidden;
    text-align: center;
    position: relative;

    iframe {
      width: 100%;
      height: 100%;
      transform: scale(.7);
      margin-top: -82px;
    }

    .expiration-mask {
      position: absolute;
      z-index: 100;
      width: 200px;
      height: 200px;
      line-height: 200px;
      top: 0px;
      left: 50px;
      text-align: center;
      font-size: 14px;
      color: #5A5D64;
      font-weight: 600;
      background-color: rgba(255, 255, 255, 0.9);
    }
  }

  /*.body .qrcode-container .qrcode {*/
  /*  display: block;*/
  /*  width: 200px;*/
  /*  height: 200px;*/
  /*  background: #DDD;*/
  /*  margin: 0 auto;*/
  /*  overflow: hidden;*/
  /*  text-align: center;*/

  /*  */
  /*}*/

  .body .qrcode-container .tips {
    position: absolute;
    top: 190px;
    width: 100%;
    font-size: 14px;
    color: #666666;

    a {
      user-select: none;
      color: #666666;
      text-decoration: underline;
      cursor: pointer;
    }
  }

  .mt-20 {
    margin-top: 20px;
  }

  .mt-30 {
    margin-top: 30px;
  }

  .mt-40 {
    margin-top: 40px;
  }

  .mt-50 {
    margin-top: 50px;
  }

  .w-100 {
    width: 100%;
  }

  .ml-5 {
    margin-left: 5px;
  }

  .cursor-pointer {
    cursor: pointer;
  }

  .spinner {
    display: inline-block;
    user-select: none;
    animation: rotation 1s linear infinite;
  }

  @keyframes rotation {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
</style>

<style lang="scss">
  .page-login {

    .custom-loign-input .el-input__inner {
      border-radius: 0;
      border-left: none;
      border-top: none;
      border-right: none;
    }

    .custom-form-item .el-form-item__error {
      padding-left: 30px;
    }

  }
</style>
